<template>
  <div>
    <el-card shadow="never" body-style="padding-bottom:0;">
      <el-row :gutter="15">
        <el-col :md="16" style="margin-bottom:15px;">
          <!-- 操作按钮 -->
          <div class="ele-table-tool ele-table-tool-default">
            <el-button type="primary" icon="el-icon-plus" class="ele-btn-icon" size="small" @click="showEdit=true">添加
            </el-button>
            <el-button
              type="warning"
              icon="el-icon-edit"
              class="ele-btn-icon"
              :disabled="!current"
              size="small"
              @click="edit"
            >修改
            </el-button>
            <el-button
              type="danger"
              icon="el-icon-delete"
              class="ele-btn-icon"
              :disabled="!current"
              size="small"
              @click="remove"
            >删除
            </el-button>
          </div>
          <!-- 数据表格 -->
          <ele-data-table
            ref="table"
            :config="table"
            :current.sync="current"
            :height="tbHeight"
            highlight-current-row
            class="dict-table"
            @done="done"
          >
            <el-table-column prop="name" label="节点名称" show-overflow-tooltip />
            <el-table-column prop="type" label="扫描器类型" show-overflow-tooltip />
            <el-table-column prop="url" label="URL" show-overflow-tooltip />
            <el-table-column prop="engine" label="扫描引擎" show-overflow-tooltip />
            <el-table-column prop="addtime" label="添加时间" show-overflow-tooltip />
            <el-table-column prop="updatetime" label="更新时间" show-overflow-tooltip />
          </ele-data-table>
        </el-col>
        <el-col :md="8" style="margin-bottom:15px;">
          <dict-data v-if="current" :dict-id="current.id" :tb-height="tbHeight" />
        </el-col>
      </el-row>
    </el-card>
    <el-card shadow="never" body-style="padding-bottom:0;">
      <div slot="header" class="clearfix">
        <span>预定义扫描</span>
        <el-button type="primary" style="float: right;" @click="isShow=true">添加</el-button>
      </div>
      <ele-data-table ref="perdefineTable" :config="perdefineTable" :border="true" height="280px">
        <template>
          <el-table-column prop="name" label="扫描名称" sortable show-overflow-tooltip min-width="110" />
          <el-table-column prop="key" label="扫描键值" sortable show-overflow-tooltip min-width="110" />
          <el-table-column prop="tasktype" label="任务类型" sortable show-overflow-tooltip min-width="110">
            <template slot-scope="{row}">{{ row.tasktype.name }}</template>
          </el-table-column>
          <el-table-column prop="updatetime" label="更新时间" sortable show-overflow-tooltip min-width="135">
            <template slot-scope="{row}">{{ row.updatetime }}</template>
          </el-table-column>
          <el-table-column label="操作" align="center" min-width="160" fixed="right">
            <template slot-scope="{row}">
              <el-link icon="el-icon-edit" type="primary" :underline="false" @click="editPerdefine(row)">修改</el-link>
              <el-popconfirm
                title="您确定删除吗？"
                @confirm="delPerdefine(scope.row.id)"
              >
                <el-link
                  slot="reference"
                  icon="el-icon-delete"
                  type="primary"
                  :underline="false"
                >删除</el-link>
              </el-popconfirm>
            </template>
          </el-table-column>
        </template>
      </ele-data-table>
    </el-card>
    <!-- 编辑弹窗 -->
    <el-dialog
      :title="editForm.dictId?'修改扫描节点':'添加扫描节点'"
      :visible.sync="showEdit"
      width="600px"
      :destroy-on-close="true"
      :lock-scroll="false"
      @closed="editForm={}"
    >
      <el-form ref="editForm" :model="editForm" :rules="editRules" label-width="110px">
        <el-form-item label="节点名称:" prop="name">
          <el-input v-model="editForm.name" placeholder="请输入节点名称" clearable />
        </el-form-item>
        <el-form-item label="扫描器类型:" prop="type">
          <el-select
            v-model="editForm.type"
            placeholder="请选择扫描器类型"
            style="width: 100%"
          >
            <el-option
              v-for="(item, key) in scnnerType"
              :key="'type' + key"
              :label="item"
              :value="item"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="URL:" prop="url">
          <el-input v-model="editForm.url" placeholder="请输入URL" clearable />
        </el-form-item>
        <el-form-item label="是否启用:" prop="status">
          <el-radio v-model="editForm.status" label="True">是</el-radio>
          <el-radio v-model="editForm.status" label="False">否</el-radio>
        </el-form-item>
        <el-form-item label="API_KEY:" prop="apikey">
          <el-input v-model="editForm.apikey" placeholder="请输入API_KEY" clearable />
        </el-form-item>
        <el-form-item label="API_SEC:" prop="apisec">
          <el-input v-model="editForm.apisec" placeholder="请输入API_SEC" clearable />
        </el-form-item>
        <el-form-item label="扫描引擎:" prop="engine">
          <el-input v-model="editForm.engine" placeholder="请输入扫描引擎" clearable />
        </el-form-item>
        <el-form-item label="节点描述:" prop="description">
          <el-input v-model="editForm.description" placeholder="请输入节点描述" :rows="4" type="textarea" />
        </el-form-item>
      </el-form>
      <div slot="footer">
        <el-button @click="showEdit=false">取消</el-button>
        <el-button type="primary" @click="save">保存</el-button>
      </div>
    </el-dialog>
    <el-dialog
      :title="perdefineEditFrom.id?'修改预定义扫描':'添加预定义扫描'"
      :visible.sync="isShow"
      width="600px"
      :destroy-on-close="true"
      :lock-scroll="false"
      @closed="perdefineEditFrom={}"
    >
      <el-form ref="perdefineEditFrom" :model="perdefineEditFrom" :rules="perdefineEditFromRules" label-width="110px">
        <el-form-item label="扫描名称:" prop="name">
          <el-input v-model="perdefineEditFrom.name" placeholder="请输入预定义名称" clearable />
        </el-form-item>
        <el-form-item label="任务类型:" prop="tasktype">
          <el-select
            v-model="perdefineEditFrom.tasktype"
            placeholder="请选择任务类型"
            style="width: 100%"
          >
            <el-option
              v-for="(item, key) in taskType"
              :key="'type' + key"
              :label="item.name"
              :value="item.id"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="扫描键值:" prop="key">
          <el-input v-model="perdefineEditFrom.key" placeholder="请输入扫描键值" clearable />
        </el-form-item>
        <el-form-item label="扫描策略:" prop="police">
          <el-select
            v-model="perdefineEditFrom.police"
            placeholder="请选择扫描策略"
            style="width: 100%"
          >
            <el-option
              v-for="(item, key) in policiesType"
              :key="'type' + key"
              :label="item.name"
              :value="item.id"
            />
          </el-select>
        </el-form-item>
      </el-form>
      <div slot="footer">
        <el-button @click="isShow=false">取消</el-button>
        <el-button type="primary" @click="savePolicies">保存</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import DictData from '../components/dictData'
export default {
  name: 'SysDictionary',
  components: { DictData },
  data() {
    return {
      table: { url: '/scanner/base/list/scanner/', where: {}},
      perdefineTable: { url: '/scanner/base/list/predefine/', where: {}},
      current: null, // 表格选中数据
      showEdit: false, // 是否显示表单弹窗
      editForm: {}, // 表单数据
      editRules: { // 表单验证规则
        name: [
          { required: true, message: '请输入节点名称', trigger: 'blur' }
        ],
        type: [
          { required: true, message: '请选择扫描器类型  ', trigger: 'blur' }
        ],
        url: [
          { required: true, message: '请输入URL', trigger: 'blur' }
        ],
        status: [
          { required: true, message: '请选择启用状态', trigger: 'blur' }
        ],
        apikey: [
          { required: true, message: '请输入API-KEY', trigger: 'blur' }
        ],
        apisec: [
          { required: true, message: '请输入API-SEC', trigger: 'blur' }
        ],
        engine: [
          { required: true, message: '请输入扫描引擎', trigger: 'blur' }
        ]
      },
      scnnerType: ['X-Ray', 'Nmap', 'DnsPod'],
      perdefineEditFrom: {},
      perdefineEditFromRules: {},
      isShow: false,
      taskType: [],
      policiesType: []
    }
  },
  computed: {
    /* 表格固定高度 */
    tbHeight() {
      return this.$store.state.theme.screenWidth < 992 ? undefined : 'calc(100vh - 600px)'
    }
  },
  watch: {
    /**
     * 监听选中扫描器的变化
     */
    current(newValue) {
      this.$http.get(`/scanner/list/policies/${newValue.id}/`).then(res => {
        this.policiesType = res.data.data
      })
    }
  },
  mounted() {
    this.getTaskType()
  },
  methods: {
    /* 表格渲染完成回调 */
    done(res) {
      if (res.data.length > 0) this.$refs.table.setCurrentRow(res.data[0])
    },
    /* 显示编辑 */
    edit() {
      this.editForm = Object.assign({}, this.current)
      this.showEdit = true
    },
    /* 保存编辑 */
    save() {
      this.$refs['editForm'].validate((valid) => {
        if (valid) {
          const loading = this.$loading({ lock: true })
          const url = this.editForm.id ? `/scanner/base/update/scanner/${this.editForm.id}/` : '/scanner/base/create/scanner/'
          this.$http.post(url, this.editForm).then(res => {
            loading.close()
            if (res.data.code === 0) {
              this.showEdit = false
              this.$message({ type: 'success', message: res.data.msg })
              this.$refs.table.reload()
            } else {
              this.$message.error(res.data.msg)
            }
          }).catch(e => {
            loading.close()
            this.$message.error(e.message)
          })
        } else {
          return false
        }
      })
    },
    /* 删除 */
    remove() {
      this.$confirm('确定要删除选中的数据吗?', '提示', { type: 'warning' }).then(() => {
        const loading = this.$loading({ lock: true })
        this.$http.get(`/scanner/base/delete/scanner/${this.current.id}`).then(res => {
          loading.close()
          if (res.data.code === 0) {
            this.$message({ type: 'success', message: res.data.msg })
            this.$refs.table.reload()
          } else {
            this.$message.error(res.data.msg)
          }
        }).catch(e => {
          loading.close()
          this.$message.error(e.message)
        })
      }).catch(() => 0)
    },
    /* 获得任务类型 */
    getTaskType() {
      this.$http.get('/task/type/select/').then(res => {
        this.taskType = res.data.data
      })
    },
    /* 保存预定义扫描 */
    savePolicies() {
      const formData = this.perdefineEditFrom
      const url = formData.id ? `/scanner/base/update/predefine/${formData.id}/` : '/scanner/base/create/predefine/'
      this.$http.post(url, formData).then(res => {
        if (res.data.code === 0) {
          this.$message({ type: 'success', message: res.data.msg })
          this.isShow = false
          this.$refs.perdefineTable.reload()
        } else {
          this.$message({ type: 'error', message: res.data.msg })
        }
      })
    },
    /* 编辑预定义扫描 */
    editPerdefine(row) {
      const data = Object.assign({}, row)
      data.tasktype = row.tasktype.id
      data.police = row.police.id
      this.perdefineEditFrom = Object.assign({}, data)
      this.isShow = true
    },
    /* 删除预定义扫描 */
    delPerdefine(row) {
      this.$http.get(`/scannner/base/delete/predefine/${row.id}`).then(res => {
        if (res.data.code === 0) {
          this.$message({ type: 'success', message: res.data.msg })
        }
      })
    }
  }
}
</script>

<style scoped>
.dict-table >>> .el-table__row {
  cursor: pointer;
}

.dict-table >>> .el-table__row > td:last-child:after {
  content: "\e6e0";
  font-family: element-icons !important;
  font-style: normal;
  font-variant: normal;
  text-transform: none;
  -webkit-font-smoothing: antialiased;
  -moz-osx-font-smoothing: grayscale;
  line-height: 1;
  position: absolute;
  right: 10px;
  top: 50%;
  margin-top: -7px;
}

.dict-table >>> .el-table__row > td:last-child .cell {
  padding-right: 20px;
}
</style>
